//
//  WBOAuthViewController.swift
//  WeiBoApp
//
//  Created by CrazyHacker on 16/7/4.
//  Copyright © 2016年 CrazyHacker. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {
    /// 懒加载授权的网页视图
    private lazy var OAuthWebView = UIWebView()

    override func loadView() {
        view = OAuthWebView
        // 设置webView的 opaque 可解决背景黑条问题
        OAuthWebView.isOpaque = false
        OAuthWebView.scrollView.backgroundColor = UIColor.white()
        OAuthWebView.backgroundColor = UIColor.white()
        title = "登录新浪微博"
        // 添加左侧返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(closeOAuthView))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // webView 加载授权网页 URL + 指定参数拼接的字符串
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppleKey)&redirect_uri=\(WBReDirectURL)"
        
        guard let url = URL(string: urlString) else {
            return
        }
        
        
        let session = URLRequest(url: url)
        OAuthWebView.loadRequest(session)
        // 禁止🚫滚动
        OAuthWebView.scrollView.isScrollEnabled = false
        // 设置 webView 的代理
        OAuthWebView.delegate = self
        
    }
    // MARK: - 自动填充方法
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '18748347786';" + "document.getElementById('passwd').value = 'liurui1314love';"
        
        // OC调用JS唯一的方法!
        OAuthWebView.stringByEvaluatingJavaScript(from: js)
        
    }
    
    // MARK: - 关闭授权界面方法
    @objc private func closeOAuthView() {
        SVProgressHUD.dismiss()
        // modal 出来的控制器, 要使用dismiss 返回
        dismiss(animated: true, completion: nil)
    }
}

//：MARK: - UIWebViewDelegate
extension WBOAuthViewController: UIWebViewDelegate {
    // webView 的代理方法 -- 将要加载数据
    /// request: 要加载的请求
    /// returns: 是否加载 request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print("加载请求---\(request.url?.absoluteString)") // 输出的请求的完整字符串
        
        // 确定授权的 授权码
        // "http://baidu.com/?code=075e4fdf0a0e6bf5e281ab5bf34106ac"
        
        // 如果返回码中有 code= 就不再加载 ==> 此时已获得授权码
        // 如果返回的URL中有 error 则需要继续请求授权
        if request.url?.absoluteString?.hasPrefix(WBReDirectURL) == false {
            return true
        }
        
        // query 就是url中？ 后面的部分
        if request.url?.query?.hasPrefix("code=") == false {
            
            closeOAuthView()
            return false
        }
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        // 加载访问授权令牌
        WebNetworkTools.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.show(withStatus: "网络请求失败")
            } else {
                // 发送通知, 告知登录成功
                NotificationCenter.default().post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
                // 关闭授权视图
                self.closeOAuthView()
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}

